﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Runtime.Remoting.Messaging;

namespace WorkStation.Frameworks.Core
{
    /// <summary>
    /// * 程序上下文
    /// </summary>
    public class ApplicationContext : Dictionary<string, object>, ILogicalThreadAffinative, IDisposable
    {
        public const string ContextKey = "WorkStation.Frameworks.Core.ApplicationContext";

        public static object LOCK_OBJECT = new object();

        private ApplicationContext()
        {

        }

        /// <summary>
        /// * 当前上下文
        /// </summary>
        public static ApplicationContext Current
        {
            get
            {
                if (HttpContext.Current != null)
                {
                    lock (ApplicationContext.LOCK_OBJECT)
                    {
                        if (HttpContext.Current.Session[ApplicationContext.ContextKey] == null)
                        {
                            HttpContext.Current.Session[ApplicationContext.ContextKey] = new ApplicationContext();
                        }
                    }
                    
                    return HttpContext.Current.Session[ApplicationContext.ContextKey] as ApplicationContext;
                }

                lock (ApplicationContext.LOCK_OBJECT)
                {
                    if (CallContext.GetData(ApplicationContext.ContextKey) == null)
                    {
                        CallContext.SetData(ApplicationContext.ContextKey, new ApplicationContext());
                    }
                }

                return CallContext.GetData(ApplicationContext.ContextKey) as ApplicationContext;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            foreach (KeyValuePair<string, object> keyValuePair in this)
            {
                IDisposable disposable = keyValuePair.Value as IDisposable;

                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }

        #endregion
    }
}
